<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\cache\driver\Redis;
class Container extends Auth
{

	public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
    }

    // 货柜装箱列表页
    public function loading(Request $request)
    {   
        if($request->isAjax()){
            // 装箱清单条件
            $delivery_at_start = isset($this->data['date']['year']) && isset($this->data['date']['month']) ? mktime(0, 0, 0, date($this->data['date']['month']), 1, date($this->data['date']['year'])) : strtotime(date('Y-m-01'));
            $delivery_at_end = isset($this->data['date']['year']) && isset($this->data['date']['month']) ? mktime(23, 59, 59, date($this->data['date']['month']), date('t'), date($this->data['date']['year'])) : mktime(23, 59, 59, date('m'), date('t'), date('Y'));
            $where['zu.delivery_day'] = ['between', $delivery_at_start . ',' . $delivery_at_end];
            $returnData =  model('Container')->getContainersContent($where,'add',$this->lang,$this->data['port_id']);
            // 补全ID，长度》3 取后三位，不够前面补0
            // array_walk_recursive($returnData,array(model('Buy'),'arrayWalkRecursive'));

            $returnData['port'] = getDatas('port',['id,name'],'1=1');
            return json_encode($returnData);
        }else{
            return view('loading',['title'=>lang("container_loading"),'next'=>lang('enter_container_adjustment'),'last'=>'仓库','last_url'=>'','fun'=>'loading']);
        }
    }

    // 货柜装箱调整列表
    public function adjust(Request $request)
    {
        if($request->isAjax()){
            $where = [];
            if(isset($this->data['container_id']) && $this->data['container_id']){
                $where['container_id'] = $this->data['container_id'];
            }
            return json_encode(model('Container')->getContainersContent($where,'edit',$this->lang));
        }else{
            return view('loading',['title'=>lang('container_adjustment'),'last'=>lang("container_loading"),'last_url'=>'admin/container/loading','fun'=>'adjust']);
        }
    }

    // 装柜
    public function addLoading()
    {
        $res = $this->addLoadingData($this->data,'add');
        return $res;
    }

    // 整理装箱数据
    function addLoadingData($data,$type)
    {   
        if(isset($data['container_id']) && $data['container_id']){
            if(!empty($data['content']['content'])){
                // 货柜信息
                $container = getDatas('container',['sum_kgs,sum_ctn,sum_cbm,sum_value'],['id'=>$data['container_id']])[0];
                $buy_po_pack_data = array_column($data['content']['content'], 'buy_po_pack');
                $true = 0;
                $msg = '';
                foreach ($buy_po_pack_data as $k => $v) {
                    foreach ($v as $k1 => $v1) { 
                        if($v1['is_che'] == 'true'){
                            $price = $v1['price'];
                            $msgContainerID = $v1['container_id'] > 0 ? $v1['container_id'] : $data['container_id'];
                            $msg .= lang('container_number').'：'.$msgContainerID.' '.lang('content').'：'.lang('product_brand').'-'.$v1['proinfo']['brand_name'].',产品名-'.$v1['proinfo']['pro_name'].','.lang('model').'-'.$v1['proinfo']['model'];
                            // 去掉不必要的元素
                            $v1 = array_diff_key($v1,['sum_qty'=>'','sum_kgs'=>'','sum_m3'=>'','price'=>'','sum_price'=>'','proinfo'=>'','is_che'=>'','maxval'=>'']);
                            $where = [
                                        'po_id'=>$v1['po_id'],
                                        'port_id'=>$v1['port_id'],
                                        'pro_id'=>$v1['pro_id'],
                                        'prochar_id'=>$v1['prochar_id'],
                                        'ctn_qty'=>$v1['ctn_qty'],
                                        'ctn_size'=>$v1['ctn_size'],
                                        'ctn_kgs'=>$v1['ctn_kgs'],
                                        'ctn_m3'=>$v1['ctn_m3'],
                                        'container_id'=>0
                                    ];
                            // $buy_po_pack_qty = getValue('buy_po_pack',$where,'qty');
                            $buy_po_pack_qty = getDatas('buy_po_pack',['id,qty'],$where);
                            $where1 = [
                                        'po_id'=>$v1['po_id'],
                                        'port_id'=>$v1['port_id'],
                                        'pro_id'=>$v1['pro_id'],
                                        'prochar_id'=>$v1['prochar_id'],
                                        'ctn_qty'=>$v1['ctn_qty'],
                                        'ctn_size'=>$v1['ctn_size'],
                                        'ctn_kgs'=>$v1['ctn_kgs'],
                                        'ctn_m3'=>$v1['ctn_m3'],
                                        'container_id'=>$v1['container_id'] == 0 ? $data['container_id'] : $v1['container_id']
                                    ];
                            $buy_po_pack = getDatas('buy_po_pack',['id,qty'],$where1);
                            /*
                            * 获取次啊狗清单的数量，同时根据查询判断提交装箱清单是否有效。
                            * 判断提交装箱清单的装箱数据是否一样，是否需要拆分装箱清单。
                            * 判断同样的装箱清单在当前货柜下已经装箱过
                            * 没有被装箱过则则直接装箱，装箱过则合并装箱清单（数量累加）
                            */
                            $qty = 0;
                            switch ($type) {
                                case 'edit':
                                    if(!empty($buy_po_pack)){
                                        // 判断同类数据为装箱的装箱单是否存在，存在则把提交的数量加上，如果并不存在则新增一个装箱清单
                                        if(!empty($buy_po_pack_qty)){
                                            $res1 = updateData('buy_po_pack',['id'=>$buy_po_pack_qty[0]['id']],['qty'=>$buy_po_pack_qty[0]['qty']+$v1['qty'] ]);
                                        }else{
                                            $v1['container_id'] = 0;
                                            unset($v1['id']);
                                            $res1 = insertData('buy_po_pack',$v1);
                                        }
                                        // dump($v1);die;
                                        $res = updateData('buy_po_pack',['id'=>$buy_po_pack[0]['id']],['qty'=>$buy_po_pack[0]['qty']-$v1['qty']]);

                                        $qty -= $v1['qty'];
                                    }else{
                                        return json_encode(array('status'=>2,lang("error_returning_stock_data")));
                                    }
                                    $msg .= lang("return_stock_quantity").$v1['qty']."。\n";
                                    break;
                                case 'add':
                                    if(!empty($buy_po_pack_qty)){
                                        /**
                                        * 判断当前提交的装箱清单的装箱数量是否相等，相等则直接绑定货柜ID
                                        * 不等则提交的装箱清单扣除提交的数量，并剩余的数量新增一个装箱清单绑定货柜信息
                                        * 
                                        * 判断当前货柜已经有同类的装箱信息，存在则追加数量，没有新增
                                        * 数量相等且同一个货柜不存在同类装箱清单信息。在新增的同时，需要删除提交的装箱信息。
                                        **/
                                        if($buy_po_pack_qty[0]['qty'] == $v1['qty']){
                                            if(empty($buy_po_pack)){
                                                $res = updateData('buy_po_pack',['id'=>$v1['id']],['container_id'=>$data['container_id']]);
                                            }else{
                                                $res = updateData('buy_po_pack',['id'=>$buy_po_pack[0]['id']],['qty'=>$v1['qty'] + $buy_po_pack[0]['qty']]);
                                                if($res){
                                                    $res1 = deleteData('buy_po_pack',['id'=>$v1['id']]);
                                                }
                                            }
                                        }else{
                                            // 拆分装箱清单
                                            $res = updateData('buy_po_pack',['id'=>$v1['id']],['qty'=>$buy_po_pack_qty[0]['qty'] - $v1['qty']]);
                                            if(empty($buy_po_pack)){
                                                $v1['container_id'] = $data['container_id'];
                                                unset($v1['id']);
                                                $res1 = insertData('buy_po_pack',$v1);
                                            }else{
                                                $res = updateData('buy_po_pack',['id'=>$buy_po_pack[0]['id']],['qty'=>$v1['qty'] + $buy_po_pack[0]['qty']]);
                                            }
                                        } 
                                        $qty += $v1['qty']; 
                                        $msg .= lang("loading_quantity").$v1['qty']."。\n";
                                    }else{
                                        return json_encode(array('status'=>2,lang("error_loading_data")));
                                    }
                                    break;
                                case 'to':  // 货柜内容转移
                                    $toContainer_ids = '';
                                    if(!empty($buy_po_pack)){
                                        // 如果数量相等则整个装箱清单转移，否则拆分装箱清单
                                        if($buy_po_pack[0]['qty'] == $v1['qty']){
                                            $res = updateData('buy_po_pack',['id'=>$buy_po_pack[0]['id']],['container_id'=>$data['container_id']]);
                                        }else{
                                            $res = updateData('buy_po_pack',['id'=>$buy_po_pack[0]['id']],['qty'=>$buy_po_pack[0]['qty']-$v1['qty']]);
                                            $v1['container_id'] = $data['container_id'];
                                            unset($v1['id']);
                                            $res = insertData('buy_po_pack',$v1);
                                        }
                                        $qty += $v1['qty'];

                                        // 重置被转移的货柜信息
                                        $toContainer = getDatas('container',['sum_kgs,sum_ctn,sum_cbm,sum_value'],['id'=>$v1['container_id']])[0];
                                        $toContainer['sum_kgs']   -= $v1['ctn_kgs'] * $v1['qty'] * $v1['ctn_qty'];
                                        $toContainer['sum_ctn']   -= $v1['qty'];
                                        $toContainer['sum_cbm']   -= $v1['ctn_m3'] * $v1['qty'] * $v1['ctn_qty'];
                                        $toContainer['sum_value'] -= $price * $v1['qty'] * $v1['ctn_qty'];
                                        $res = updateData('container',['id'=>$v1['container_id']],$toContainer);
                                        $msg .= lang('transfer_to_number').'：'.$v1['container_id'].' '.lang('quantity_of_container').'-'.$v1['qty']."。\n";
                                    }else{
                                        return json_encode(array('status'=>2,lang("data_transmission_error")));
                                    }
                                    break;
                            }
                            $container['sum_kgs']   += $v1['ctn_kgs'] * $qty * $v1['ctn_qty'];
                            $container['sum_ctn']   += $qty;
                            $container['sum_cbm']   += $v1['ctn_m3'] * $qty * $v1['ctn_qty'];
                            $container['sum_value'] += $price * $qty * $v1['ctn_qty'];
                            $true++;

                        }
                    }
                }
                if($true){
                    $res = updateData('container',['id'=>$data['container_id']],$container);
                    if($res){
                        return json_encode(array('status'=>1,'msg'=>$msg.' '.lang('successfully')));
                    }else{
                        return json_encode(array('status'=>0,'msg'=>$msg.' '.lang('failed')));
                    }
                }else{
                    return json_encode(array('status'=>2,'msg'=>lang("please_select_the_packing_list_to_be_operated")));
                }
                
            }else{
                return json_encode(array('status'=>2,'msg'=>lang("please_select_the_packing_list_to_be_operated")));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang("please_select_the_correct_container")));
        }
    }


    // 货柜调整
    public function editAdjust()
    {
        $res = $this->addLoadingData($this->data,'edit');
        return $res;
    }


    // 货柜内容转移
    public function toContainer()
    {
        $res = $this->addLoadingData($this->data,'to');
        return $res;
    }



}
